/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-16 下午6:44
 */

package com.lenovo.mso2o.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.lenovo.framework.base.InjectableFragment;
import com.lenovo.framework.rx.RxBus;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.view.ContentLoaderView;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.entity.g.Notification;
import com.lenovo.mso2o.entity.g.NotificationDao;
import com.lenovo.mso2o.service.GetuiPushReceiver;
import com.lenovo.mso2o.ui.adapter.NotificationAdapter;

import java.util.List;

import butterknife.Bind;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;

public class NotificationFragment extends InjectableFragment implements ContentLoaderView.OnRefreshListener, ContentLoaderView.OnMoreListener, NotificationAdapter.OnNotificationSelectedListener {

    public static final String KEY_NOTIFICATION = "key_notification";

    @Bind(R.id.content_loader)
    ContentLoaderView loaderView;
    @Bind(R.id.recycler)
    XRecyclerView recyclerView;

    NotificationDao dao;
    NotificationAdapter adapter;
    private RxBus _rxBus;
    private CompositeSubscription _subscriptions;
    private View rootView;
    private static final int FRAGMENT_MESSAGE = 5;
//    private MyBroadcastReciver myBroadcastReciver;
    public static Fragment newInstance() {
        NotificationFragment fragment = new NotificationFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        /*ArrayList<Notification> l = new ArrayList<Notification>();
        if (adapter != null) {
            l.addAll(adapter.getNotificationList());
            outState.putParcelableArrayList(KEY_NOTIFICATION, l);
        }
        */
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView != null) return rootView;
        // Inflate the layout for this fragment
        View view = super.onCreateView(inflater, container, savedInstanceState);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setLoadingMoreEnabled(false);
        recyclerView.setRefreshProgressStyle(ProgressStyle.BallPulse);
        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //refresh data here
                loadData(1);
                recyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                // load more data here
            }
        });

        adapter = new NotificationAdapter(getActivity());
        adapter.setOnNotificationSelectedListener(this);

        loaderView.setAdapter(adapter, FRAGMENT_MESSAGE);
        loaderView.setOnRefreshListener(this);
        loaderView.setMoreListener(this);

        dao = MSApplication.getDaoSession().getNotificationDao();
        /*
        if (savedInstanceState != null) {
            List<Notification> anchorList = savedInstanceState.getParcelableArrayList(KEY_NOTIFICATION);
            adapter.setListData(anchorList);
            adapter.notifyDataSetChanged();
        } else {
        */
            loadData(1);
        //}
        return rootView = view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        _rxBus = MSApplication.getRxBus();
    }


    @Override
    public void onStart() {
        super.onStart();
        _subscriptions = new CompositeSubscription();

        _subscriptions//
                .add(_rxBus.toObserverable()//
                        .subscribe(new Action1<Object>() {
                            @Override
                            public void call(Object event) {
                                if (event.equals(GetuiPushReceiver.NEW_NOTIFICATION)) {
                                    loadData(1);
                                }
                            }
                        }));
    }


    @Override
    public void onStop() {
        super.onStop();
        if(_subscriptions != null)
            _subscriptions.unsubscribe();
    }

    @Override
    public int provideContentRes() {
        return R.layout.fragment_list;
    }

    @Override
    protected void onFragmentVisible(Bundle savedInstanceState) {

    }

    public void loadData(final int page) {
        try {
            List<Notification> list = dao.queryBuilder().orderDesc(NotificationDao.Properties.Date).offset((page - 1) * MSConstants.PAGE_SIZE).limit(MSConstants.PAGE_SIZE).list();
            if (page == 1) {
                adapter.setListData(list);
            } else {
                adapter.addMoreData(list);
            }
            adapter.notifyDataSetChanged();
            if (list.size() < MSConstants.ListParamConstants.pageSize_default) {
                loaderView.setPage(page, page);//最后一页数据少于约定数据量，停止加载
            } else {
                loaderView.setPage(page, page + 1);//设置当前页和最后一页
            }

        } catch (Exception e) {
            if (loaderView != null)
                loaderView.notifyLoadFailed(e.getCause());
            DLog.d("onNext %s", "" + e);
        }
    }


    @Override
    public void onRefresh(boolean fromSwipe) {
        loadData(1);
    }

    @Override
    public void onMore(int page) {
        loadData(page);
    }

    @Override
    public void onNotificationSelected(Notification notification) {
        DLog.toast("selected order_item" + notification.toString());
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (rootView != null) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    protected void onFragmentInVisible(Bundle savedInstanceState) {

    }
}
